<template>
  <van-popup
    v-model="modleShow1"
    closeable
    close-icon-position="top-left"
    position="bottom"
    :style="{ height: '100%' }"
    get-container="body"
    @click-close-icon="$emit('update:show', false)"
  >
    <div class="content-wrap">
      <div class="content">
        <van-cell
          title="我的频道"
          center
          :border="false"
        >
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <van-button size="small" plain round type="warning" @click="isEdit = !isEdit">{{ isEdit ? '完成' : '编辑'}}</van-button>
          </template>
        </van-cell>
        <van-grid :border="false">
          <van-grid-item
           v-for="(channel, index) in channels"
           :key="channel.id"
           :text="channel.name"
           :class="{active: active === index}"
           icon-prefix="iconfont"
           :icon="(isEdit && (index !== 0)) ? 'guanbi' : '' "
           @click="clickMyChannel(channel, index)"
          />
        </van-grid>
      </div>
      <div class="content">
        <van-cell
          title="频道推荐"
          center
          :border="false"
        >
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <!-- <template #right-icon>
            <van-button size="small" plain round type="warning">编辑</van-button>
          </template> -->
        </van-cell>
        <van-grid :border="false">
          <van-grid-item
            v-for="channel in recommendChannels"
            :key="channel.id"
            :text="channel.name"
            @click="addToMyChannels(channel)"
          />
        </van-grid>
      </div>
    </div>
  </van-popup>
</template>

<script>
import { requestAllChannels, requestAddChannel, requestDeleteChannel } from '@/api/home.js'
import { setStorage } from '@/utils/storage.js'

export default {
  name: 'EditChannels',
  props: {
    // 弹框显现
    show: {
      type: Boolean,
      required: true,
      default: false
    },
    // 我的频道
    channels: {
      type: Array,
      required: true
    },
    // 激活的标签号
    active: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      // 总的频道
      allChannels: [],
      modleShow: this.show,
      // 编辑频道状态,false不编辑，true编辑
      isEdit: false
    }
  },
  created () {
    this.getAllChannels()
  },
  computed: {
    // 拿取chanels（因为props的数据最好不要更改，故而将其初始化到data）
    // myChannels () {
    //   return this.channels
    // },
    // 推荐频道，总的频道减去我的频道
    recommendChannels () {
      return this.allChannels.filter(channel => {
        // console.log(channel.id, '测试')
        for (let i = 0; i < this.channels.length; i++) {
          if (channel.id === this.channels[i].id) {
            console.log(channel.name, channel.id, this.channels[i].id, channel.id === this.channels[i].id)
            return false
          }
        }
        return true
      })
    },
    modleShow1: {
      get: function () {
        return this.show
      },
      set: function (newVal) {
        // console.log(newVal)
      }
    }
  },
  methods: {
    async getAllChannels () {
      try {
        const { data } = await requestAllChannels()
        this.allChannels = data.data.channels
        console.dir(data)
      } catch (err) {
        console.log(err, '食不安')
      }
    },
    // 添加频道推荐里的频道到我的频道
    async addToMyChannels (channel) {
      const channels = this.channels
      channels.push(channel)
      // 添加到我的频道，利用自定义事件直接将数据更新到父组件，子组件的props会自动更新（单向数据流）
      this.$emit('update:channels', channels)
      // 数据持久化
      if (this.$store.state.userToken) {
        // 如果已登录
        // 同时，添加的频道要同步到数据库，发送请求
        await requestAddChannel(
          [
            {
              id: channel.id,
              seq: channels.length
            }
          ]
        )
      } else {
        // 如果未登录,存到localstorage
        setStorage('userChannels', channels)
      }
    },
    // 点击我的频道
    clickMyChannel (channel, index) {
      // console.log(channel, index)
      if (this.isEdit && (index !== 0)) {
        // 当isEdit为true时，删除频道
        this.deleteChannel(channel, index)
      } else {
        // 当isEdit为false时，跳转频道
        // 更新父组件的active
        this.$emit('update:active', index)
        // 并关闭当前弹框页面
        this.$emit('update:show', false)
        // 如果isEdit为true重置编辑
        if (this.isEdit) {
          this.isEdit = false
        }
      }
    },

    // 删除频道
    async deleteChannel (channel, index) {
      const channels = this.channels
      // 如果当前删除的频道标识符号小于等于当前激活的频道表示符号，需要将当前激活标识符减1
      if (index <= this.active) {
        const activeIndex = this.active - 1
        this.$emit('update:active', activeIndex)
      }
      channels.splice(index, 1)
      // 添加到我的频道，利用自定义事件直接将数据更新到父组件，子组件的props会自动更新（单向数据流）
      this.$emit('update:channels', channels)
      // 数据持久化
      if (this.$store.state.userToken) {
        // 如果已登录
        // 同时，删除的频道要同步到数据库，发送请求
        await requestDeleteChannel(channel.id)
      } else {
        // 如果未登录,存到localstorage
        setStorage('userChannels', channels)
      }
    }
  }
  // watch: {
  //   show: function (val) {
  //     // console.log(val, '改了')
  //     this.modleShow = val
  //   }
  // }
}

</script>
<style scoped lang="less">
.content-wrap {
  padding-top: 45px;
  .content {
    padding-top: 10px;
    .van-cell {
      height: 34px;
      padding: 0 12px;
      font-size: 16px;
      .van-button {
        width: 50px;
        height: 24px;
        font-size: 14px;
        color: #f85f5f;
      }
    }
    .van-grid {
      padding: 18px 0 18px 11px;
      .van-grid-item {
        padding-right: 11px;
        padding-bottom: 11px;
        /deep/ .van-grid-item__content {
          height: 44px;
          padding: 0;
          background-color: #F4F5F6;
          border-radius: 5px;
          .van-grid-item__text {
            font-size: 14px;
            color: #222;
            margin: 0;
          }
          .iconfont-guanbi {
            position: absolute;
            right: 4px;
            top: -10px;
            border: 1px solid #222;
            color: #222;
            border-radius: 50%;
            font-size: 10px;
            padding: 6px;
            transform: scale(.6);
          }
        }
        &.active /deep/ .van-grid-item__content .van-grid-item__text{
          color:  #f85f5f;
        }
      }
    }
  }
}
</style>
